package com.qf.boot2302.service.impl;

import cn.hutool.core.io.FileUtil;
import com.qf.boot2302.service.UserService;
import com.qf.boot2302.util.QfRandomUtil;
import com.qf.pickname.spring.boot.autoconfigure.util.PicknameOOP;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import java.util.Set;

@Service
@Slf4j
public class UserServiceImpl implements UserService {

    @Autowired
    PicknameOOP picknameOOP;

    @Override
    public String pickname() throws Exception {

//        String filepath = "D:\\2302\\names.txt";
//        PicknameOOP picknameOOP = new PicknameOOP(filepath);
        String randomname = picknameOOP.randomname();

        return randomname;
    }

    @Override
    public List<String> picknamewithnum(Integer num) throws Exception {
        //0. 读取文本文件中的内容到List中
        String filepath = "D:\\2302\\names.txt";
        List<String> namelist = FileUtil.readLines(filepath, "utf-8");
        //1. 参数num个随机数
        Set<Integer> indexSet = QfRandomUtil.produceRandomNum(num, namelist.size());
        //2. 获取随机数对应的名字
        ArrayList<String> resultList = new ArrayList<>();
        for (Integer index : indexSet) {
            resultList.add(namelist.get(index));
        }
        return resultList;
    }

    @Override
    public String picknamefair(Boolean fair) throws Exception {

        if (fair){
            // 公平点名的处理流程如下
            //0. 读取文本文件中的内容到List中
            String filepath = "D:\\2302\\names.txt";
            List<String> nameList = FileUtil.readLines(filepath, "utf-8");
            //1. 读取已经点过名字的文本文件
            String pickedpath = "D:\\2302\\picked.txt";
            List<String> pickedList = FileUtil.readLines(pickedpath, "utf-8");
            log.info("已经点过的名单为:pickedList={}",pickedList);
            //2. 求两个集合的差集
            nameList.removeAll(pickedList);
            log.info("差集为:nameList={}",nameList);
            if (nameList.size()>0){
                //3. 产生随机数，上限是差集的长度
                int index = new Random().nextInt(nameList.size());
                //4. 获取下表的名字
                String name = nameList.get(index);
                log.info("中奖的同学为:name={}",name);
                //5. 把中奖的同学，写入pickedpath文件中
                FileUtil.appendString(name,pickedpath,"utf-8");
                FileUtil.appendString("\r\n",pickedpath,"utf-8");
                return name;
            }else {
                return "都点完了，请重置";
            }

        }else {
            // 非公平点名
            String pickname = pickname();
            return pickname;
        }

    }

    @Override
    public void reset() {
        String filepath = "D:\\2302\\picked.txt";
        FileUtil.writeString("",filepath,"utf-8");
    }
}
